package com.xcc.core.netty;

import com.xcc.core.netty.server.HeartBeatRespHandler;
import com.xcc.core.netty.server.ServerHandler2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class CustomAgreementServer {

    public static void main(String[] args) throws Exception {
        bind(10087);
    }
    
    public static void bind(int port) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(); //bossGroup就是parentGroup，是负责处理TCP/IP连接的
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //workerGroup就是childGroup,是负责处理Channel(通道)的I/O事件
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {  // 绑定客户端连接时候触发操作
                @Override
                protected void initChannel(SocketChannel sh) throws Exception {
                    sh.pipeline()
//                    .addLast(new NettyMessageDecoder(1024 * 1024, 4, 4))
//                    .addLast(new NettyMessageEncoder())
//                    .addLast("readTimeoutHandler", new ReadTimeoutHandler(50))
                    .addLast(new HeartBeatRespHandler());
                    
           
                }
            });
            //绑定监听端口，调用sync同步阻塞方法等待绑定操作完
            ChannelFuture future = sb.bind(port).sync();

            if (future.isSuccess()) {
                System.out.println("10087服务端启动成功");
            } else {
                System.out.println("服务端启动失败");
                future.cause().printStackTrace();
                bossGroup.shutdownGracefully(); //关闭线程组
                workerGroup.shutdownGracefully();
            }
            future.channel().closeFuture().sync();
        }
        catch (Exception e) {
          e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        } 
    }
}
